package com.sunseen.capacitormachine.modules.parameter.productparameter.modify;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import androidx.databinding.ViewDataBinding;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bin.david.form.core.SmartTable;
import com.bin.david.form.data.column.Column;
import com.bin.david.form.data.format.selected.BaseSelectFormat;
import com.bin.david.form.data.table.FormTableData;
import com.bin.david.form.data.table.TableData;
import com.sunseen.capacitormachine.R;
import com.sunseen.capacitormachine.commumication.http.HttpUtil;
import com.sunseen.capacitormachine.commumication.http.RestClient;
import com.sunseen.capacitormachine.data.DataUtil;
import com.sunseen.capacitormachine.databinding.FragmentModifyProductFlowBinding;
import com.sunseen.capacitormachine.common.BaseFragment;
import com.sunseen.capacitormachine.modules.parameter.bean.FlowCardBean;
import com.sunseen.capacitormachine.common.Form;
import com.sunseen.capacitormachine.modules.parameter.productivetask.event.ModifyParameterEvent;

import org.greenrobot.eventbus.EventBus;

/**
 * @author zest
 */
public class ModifyProductFlowFragment extends BaseFragment {
    @Override
    protected int setLayout() {
        return R.layout.fragment_modify_product_flow;
    }

    private Form selectForm;
    private int curCol = -1;
    private int curRow = -1;

    private SmartTable<Form> table;

    @Override
    protected void onBindView(ViewDataBinding viewDataBinding) {
        initForm();
        FragmentModifyProductFlowBinding binding = (FragmentModifyProductFlowBinding) viewDataBinding;
        table = binding.tableParameter;
        table.getConfig().setShowXSequence(false);
        table.getConfig().setShowYSequence(false);
        table.getConfig().setShowTableTitle(false);
        table.getConfig().getContentGridStyle()
                .setColor(getResources().getColor(R.color.table_content_grid_color));
        table.getConfig().getContentStyle()
                .setTextColor(getResources().getColor(R.color.table_content_text_color));
        table.setSelectFormat(new BaseSelectFormat());

        FormTableData<Form> tableData = FormTableData.create(table, "", 32, form);
        tableData.setFormat((Form form) -> {
            if (form != null) {
                return form.getContent();
            } else {
                return "";
            }
        });
        tableData.setOnItemClickListener(new TableData.OnItemClickListener<Form>() {
            @Override
            public void onClick(Column column, String value, Form form, int col, int row) {
                if (form != null) {
                    if ((col % 8) == 0) {
                        //列数从0开始，偶数列为属性名称，不可更改
                        binding.btnInput.setEnabled(false);
                        curCol = -1;
                        curRow = -1;
                    } else {
                        binding.btnInput.setEnabled(true);
                        selectForm = form;
                        curCol = col;
                        curRow = row;
                    }
                }
            }
        });
        table.setTableData(tableData);
        Bundle bundle = getArguments();
        if (bundle != null) {
            String batchId = bundle.getString("batchId");
            if (batchId != null) {
                queryFlowCard(batchId);
            }
        }
        binding.btnInput.setOnClickListener((View v) -> {
            if (selectForm != null) {
                String content = binding.editInput.getText().toString();
                switch (curCol) {
                    case 1: {
                        switch (curRow) {
                            case 0: {
                                Toast.makeText(_mActivity, getString(R.string.batch_id_prohibit_modify), Toast.LENGTH_SHORT).show();
                            }
                            break;
                            case 1: {
                                EventBus.getDefault().post(new ModifyParameterEvent("specification", content));
                            }
                            break;
                            case 2: {
                                EventBus.getDefault().post(new ModifyParameterEvent("positiveFoilModel", content));
                            }
                            break;
                            case 3: {
                                EventBus.getDefault().post(new ModifyParameterEvent("negativeFoilModel", content));
                            }
                            break;
                            case 4: {
                                EventBus.getDefault().post(new ModifyParameterEvent("guildPinSupplier", content));
                            }
                            break;
                            case 5: {
                                EventBus.getDefault().post(new ModifyParameterEvent("electrolyticPaper1Remark", content));
                            }
                            break;
                            case 6: {
                                EventBus.getDefault().post(new ModifyParameterEvent("electrolyte", content));
                            }
                            break;
                            case 7: {
                                EventBus.getDefault().post(new ModifyParameterEvent("coverSupplier", content));
                            }
                            break;
                            case 8: {
                                EventBus.getDefault().post(new ModifyParameterEvent("aluminumShellRemark", content));
                            }
                            break;
                        }
                    }
                    break;
                    case 9: {
                        switch (curRow) {
                            case 0: {
                                EventBus.getDefault().post(new ModifyParameterEvent("productCode", content));
                            }
                            break;
                            case 1: {
                                EventBus.getDefault().post(new ModifyParameterEvent("size", content));
                            }
                            break;
                            case 2: {
                                EventBus.getDefault().post(new ModifyParameterEvent("positiveFoilSupplier", content));
                            }
                            break;
                            case 3: {
                                EventBus.getDefault().post(new ModifyParameterEvent("negativeFoilSupplier", content));
                            }
                            break;
                            case 4: {
                                EventBus.getDefault().post(new ModifyParameterEvent("guildPinRemark", content));
                            }
                            break;
                            case 5: {
                                EventBus.getDefault().post(new ModifyParameterEvent("electrolyticPaper2", content));
                            }
                            break;
                            case 6: {
                                EventBus.getDefault().post(new ModifyParameterEvent("electrolyteSupplier", content));
                            }
                            break;
                            case 7: {
                                EventBus.getDefault().post(new ModifyParameterEvent("coverRemark", content));
                            }
                            break;
                            case 8: {
                                EventBus.getDefault().post(new ModifyParameterEvent("casing", content));
                            }
                            break;
                        }
                    }
                    break;
                    case 17: {
                        switch (curRow) {
                            case 0: {
                                EventBus.getDefault().post(new ModifyParameterEvent("customerCode", content));
                            }
                            break;
                            case 1: {
                                EventBus.getDefault().post(new ModifyParameterEvent("amount", content));
                            }
                            break;
                            case 2: {
                                EventBus.getDefault().post(new ModifyParameterEvent("positiveFoilSize", content));

                            }
                            break;
                            case 3: {
                                EventBus.getDefault().post(new ModifyParameterEvent("negativeFoilSize", content));
                            }
                            break;
                            case 4: {
                                EventBus.getDefault().post(new ModifyParameterEvent("electrolyticPaper1", content));
                            }
                            break;
                            case 5: {
                                EventBus.getDefault().post(new ModifyParameterEvent("electrolyticPaper2Supplier", content));
                            }
                            break;
                            case 6: {
                                EventBus.getDefault().post(new ModifyParameterEvent("electrolyteRemark", content));
                            }
                            break;
                            case 7: {
                                EventBus.getDefault().post(new ModifyParameterEvent("aluminumShell", content));
                            }
                            break;
                            case 8: {
                                EventBus.getDefault().post(new ModifyParameterEvent("casingSupplier", content));
                            }
                            break;
                        }
                    }
                    break;
                    case 25: {
                        switch (curRow) {
                            case 0: {
                                EventBus.getDefault().post(new ModifyParameterEvent("date", content));
                            }
                            break;
                            case 1: {
                                EventBus.getDefault().post(new ModifyParameterEvent("capacityRange", content));
                            }
                            break;
                            case 2: {
                                EventBus.getDefault().post(new ModifyParameterEvent("positiveFoil", content));
                            }
                            break;
                            case 3: {
                                EventBus.getDefault().post(new ModifyParameterEvent("guildPinModel", content));
                            }
                            break;
                            case 4: {
                                EventBus.getDefault().post(new ModifyParameterEvent("electrolyticPaper1Supplier", content));
                            }
                            break;
                            case 5: {
                                EventBus.getDefault().post(new ModifyParameterEvent("electrolyticPaper2Remark", content));
                            }
                            break;
                            case 6: {
                                EventBus.getDefault().post(new ModifyParameterEvent("cover", content));
                            }
                            break;
                            case 7: {
                                EventBus.getDefault().post(new ModifyParameterEvent("aluminumShellSupplier", content));
                            }
                            break;
                            case 8: {
                                EventBus.getDefault().post(new ModifyParameterEvent("casingRemark", content));
                            }
                            break;
                        }
                    }
                    break;
                }
                if (curCol != 1 || curRow != 0) {
                    selectForm.setContent(content);
                    binding.tableParameter.invalidate();
                    binding.editInput.setText("");
                }
            }
        });
    }

    private Form[][] form = null;

    private void initForm() {
        form = new Form[][]{
                {
                        new Form(getString(R.string.batch_id)),
                        new Form("", 7),
                        new Form(getString(R.string.product_code)),
                        new Form("", 7),
                        new Form(getString(R.string.customer_code)),
                        new Form("", 7),
                        new Form(getString(R.string.fill_table_date)),
                        new Form("", 7)
                },
                {
                        new Form(getString(R.string.specification)),
                        new Form("", 7),
                        new Form(getString(R.string.size)),
                        new Form("mm", 7),
                        new Form(getString(R.string.order_quantity)),
                        new Form("颗", 7),
                        new Form(getString(R.string.range_of_capacity)),
                        new Form("", 7)
                },
                {
                        new Form(getString(R.string.positive_foil_type)),
                        new Form("", 7),
                        new Form(getString(R.string.positive_foil_supplier)),
                        new Form("", 7),
                        new Form(getString(R.string.positive_foil_size)),
                        new Form("", 7),
                        new Form(getString(R.string.positive_foil_specific_volume)),
                        new Form("", 7),
                },

                {
                        new Form(getString(R.string.negative_foil_type)),
                        new Form("", 7),
                        new Form(getString(R.string.negative_foil_supplier)),
                        new Form("", 7),
                        new Form(getString(R.string.negative_foil_size)),
                        new Form("", 7),
                        new Form(getString(R.string.guide_pin_type)),
                        new Form("", 7),
                },
                {
                        new Form(getString(R.string.guide_pin_supplier)),
                        new Form("", 7),
                        new Form(getString(R.string.guide_pin_remark)),
                        new Form("", 7),
                        new Form(getString(R.string.electrolytic_paper)),
                        new Form("", 7),
                        new Form(getString(R.string.electrolytic_paper_supplier)),
                        new Form("", 7),
                },
                {
                        new Form(getString(R.string.electrolytic_paper_remark)),
                        new Form("", 7),
                        new Form(getString(R.string.electrolytic_paper_2)),
                        new Form("", 7),
                        new Form(getString(R.string.electrolytic_paper_supplier_2)),
                        new Form("", 7),
                        new Form(getString(R.string.electrolytic_paper_remark_2)),
                        new Form("", 7),
                },
                {
                        new Form(getString(R.string.electrolyte)),
                        new Form("", 7),
                        new Form(getString(R.string.electrolyte_supplier)),
                        new Form("", 7),
                        new Form(getString(R.string.electrolyte_remark)),
                        new Form("", 7),
                        new Form(getString(R.string.cover)),
                        new Form("", 7),
                },
                {
                        new Form(getString(R.string.cover_supplier)),
                        new Form("", 7),
                        new Form(getString(R.string.cover_remark)),
                        new Form("", 7),
                        new Form(getString(R.string.aluminum_case)),
                        new Form("", 7),
                        new Form(getString(R.string.aluminum_case_supplier)),
                        new Form("", 7),
                },
                {
                        new Form(getString(R.string.aluminum_case_remark)),
                        new Form("", 7),
                        new Form(getString(R.string.drive_pipe)),
                        new Form("", 7),
                        new Form(getString(R.string.drive_pipe_supplier)),
                        new Form("", 7),
                        new Form(getString(R.string.drive_pipe_remark)),
                        new Form("", 7),
                },
        };
    }


    private String getNoNullStr(String str) {
        return str == null ? "" : str;
    }

    private void queryFlowCard(String batchId) {
        RestClient.builder()
                .url(HttpUtil.FlowCard + "/" + batchId)
                .params("deviceNo", DataUtil.DeviceNo)
                .success((String respond) -> {
                    JSONObject rootObj = JSON.parseObject(respond);
                    if (rootObj != null) {
                        int status = rootObj.getIntValue("status");
                        if (status == 1) {
                            JSONObject dataObj = rootObj.getJSONObject("data");
                            if (dataObj != null) {
                                FlowCardBean bean = JSON.parseObject(
                                        dataObj.getJSONObject("item").toJSONString(),
                                        FlowCardBean.class);
                                if (bean != null) {
                                    updateForm(bean);
                                } else {
                                    Toast.makeText(_mActivity, "流转卡查询结果为空", Toast.LENGTH_SHORT).show();
                                    Log.e("test", "流转卡查询结果为空");
                                }
                            } else {
                                Toast.makeText(_mActivity, "流转卡查询结果为空", Toast.LENGTH_SHORT).show();
                                Log.e("test", "流转卡查询结果为空:");
                            }
                        } else {
                            String msg = rootObj.getString("message");
                            if (msg == null) {
                                msg = "未知原因";
                            }
                            Toast.makeText(_mActivity, "流转卡查询失败: " + msg, Toast.LENGTH_SHORT).show();
                            Log.e("test", "流转卡查询失败: " + msg);
                        }
                    } else {
                        Toast.makeText(_mActivity, "流转卡查询失败", Toast.LENGTH_SHORT).show();
                        Log.e("test", "流转卡查询失败,根数据为空");
                    }
                })
                .failure(() -> {
                    Toast.makeText(_mActivity, "流转卡查询结果失败", Toast.LENGTH_SHORT).show();
                    Log.e("test", "流转卡查询结果失败");
                })
                .error((code, msg) -> {
                    Toast.makeText(_mActivity, "流转卡查询结果错误", Toast.LENGTH_SHORT).show();
                    Log.e("test", "流转卡查询结果错误 " + code + " " + msg);
                })
                .build()
                .get();
    }

    private void updateForm(FlowCardBean bean) {
        Log.e("test", "updateForm in modify mode");
        if (isAdded() && getActivity() != null) {
            form[0][1].setContent(bean.getBatchId());
            form[0][3].setContent(getNoNullStr(bean.getProductCode()));
            form[0][5].setContent(getNoNullStr(bean.getCustomerCode()));
            form[0][7].setContent(getNoNullStr(bean.getDate()));
            form[1][1].setContent(getNoNullStr(bean.getSpecification()));
            form[1][3].setContent(getNoNullStr(bean.getSize()));
            form[1][5].setContent(getNoNullStr(bean.getAmount()));
            form[1][7].setContent(getNoNullStr(bean.getCapacityRange()));
            form[2][1].setContent(getNoNullStr(bean.getPositiveFoilModel()));
            form[2][3].setContent(getNoNullStr(bean.getPositiveFoilSupplier()));
            form[2][5].setContent(getNoNullStr(bean.getPositiveFoilSize()));
            form[2][7].setContent(getNoNullStr(bean.getPositiveFoil()));
            form[3][1].setContent(getNoNullStr(bean.getNegativeFoilModel()));
            form[3][3].setContent(getNoNullStr(bean.getNegativeFoilSupplier()));
            form[3][5].setContent(getNoNullStr(bean.getNegativeFoilSize()));
            form[3][7].setContent(getNoNullStr(bean.getGuildPinModel()));
            form[4][1].setContent(getNoNullStr(bean.getGuildPinSupplier()));
            form[4][3].setContent(getNoNullStr(bean.getGuildPinRemark()));
            form[4][5].setContent(getNoNullStr(bean.getElectrolyticPaper1()));
            form[4][7].setContent(getNoNullStr(bean.getElectrolyticPaper1Supplier()));
            form[5][1].setContent(getNoNullStr(bean.getElectrolyticPaper1Remark()));
            form[5][3].setContent(getNoNullStr(bean.getElectrolyticPaper2()));
            form[5][5].setContent(getNoNullStr(bean.getElectrolyticPaper2Supplier()));
            form[5][7].setContent(getNoNullStr(bean.getElectrolyticPaper2Remark()));
            form[6][1].setContent(getNoNullStr(bean.getElectrolyte()));
            form[6][3].setContent(getNoNullStr(bean.getElectrolyteSupplier()));
            form[6][5].setContent(getNoNullStr(bean.getElectrolyteRemark()));
            form[6][7].setContent(getNoNullStr(bean.getCover()));
            form[7][1].setContent(getNoNullStr(bean.getCoverSupplier()));
            form[7][3].setContent(getNoNullStr(bean.getCoverRemark()));
            form[7][5].setContent(getNoNullStr(bean.getAluminumShell()));
            form[7][7].setContent(getNoNullStr(bean.getAluminumShellSupplier()));
            form[8][1].setContent(getNoNullStr(bean.getAluminumShellRemark()));
            form[8][3].setContent(getNoNullStr(bean.getCasing()));
            form[8][5].setContent(getNoNullStr(bean.getCasingSupplier()));
            form[8][7].setContent(getNoNullStr(bean.getCasingRemark()));
            table.invalidate();
        }
    }
}
